package com.sunda.spmsweb.oacontroller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmscommon.feign.IFeignServiceCommon;
import com.sunda.spmscommon.service.ISysLogMqService;
import com.sunda.spmsorder.service.IMaterialApplicationService;
import com.sunda.spmsorder.service.IOrderWerksService;
import com.sunda.spmsoversea.service.IOverseaInvCheckActionService;
import com.sunda.spmsoversea.service.IOverseaWhsDumpService;
import com.sunda.spmsuser.entity.SpmsUser;
import com.sunda.spmsuser.service.ISpmsUserService;
import com.sunda.spmsweb.aspect.Login;
import com.sunda.spmsweb.aspect.Operation;
import com.sunda.spmsweb.ibmmqservice.SendMessageInterface;
import com.sunda.spmsweb.oaservice.OaService;
import com.sunda.spmsweb.util.JWTUtil;
import com.sunda.spmsweb.util.MD5Utils;
import feign.FeignException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.UUID;

import static com.sunda.spmscommon.Constans.*;

/**
 * @program: spms
 * @description: OA Auth Controller
 * @author: Wayne Wu
 * @create: 2020-10-27 15:49
 **/
@Slf4j
@RestController
@RequestMapping("/oa")
@Api(tags = "OA相关接口", description = "OA相关接口")
public class oacontroller {

    @Autowired
    ISpmsUserService iSpmsUserService;

    @Autowired
    IOrderWerksService iOrderWerksService;

    @Autowired
    SendMessageInterface sendMessageInterface;

    @Autowired
    IMaterialApplicationService iMaterialApplicationService;

    @Autowired
    IOverseaInvCheckActionService iOverseaInvCheckActionService;

    @Autowired
    IOverseaWhsDumpService iOverseaWhsDumpService;

    @Autowired
    IFeignServiceCommon iFeignServiceCommon;

    @Autowired
    ISysLogMqService iSysLogMqService;

    @Value("${oa.token}")
    String token;

    /** @Login 监控登录用户记录日志; 用户登录，成功则返回用户相关信息——用户个人信息、角色、权限、工厂、车间 配置信息 */
    @Login(operateType = "登录")
    @RequestMapping(value = "/login")
    @ApiOperation(value = "OA用户登陆获取 token 信息",notes = "token = " +
            "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTc3NTY2NjJ9.Z5DGPyA10VBF1WC77GprP-Llv-O8ySHhmRUGV-h7tU0\n\n" +
            "OA系统请求路径参考：\nhttp://192.168.106.90/external/#/external/oaview?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTc5MzQ0ODEsInVzZXJJZCI6Ijk5OTk0NyJ9.DcXsnU41dfKKbXWx15ZreieNy6hFhqyaR2ezsUuP_Bc&spmsId=GF03-2021-003"
            , httpMethod = "POST")
    public ResponseResult login(String userId, String accesskey) {
        try {
            //校验令牌，正确的话发放新的令牌；否则返回错误信息；
            if (accesskey.equals(token)){
                SpmsUser user = iSpmsUserService.getByUserId(userId);
                if (user == null){
                    OaService oaService = new OaService();
                    Map<String, Object> map = oaService.getUserInfo(userId);
                    if (map == null){
                        return ResponseResult.loginError("Access denied.");
                    }
                    String MDPassword = MD5Utils.encrypt(userId, "12345678");
                    iSpmsUserService.oaCreateSpmsUser(map, MDPassword);
                }
                return ResponseResult.success().add("token", JWTUtil.createOaToken(userId));
            }
            return ResponseResult.loginError("Access denied.");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("e===" + e);
            return ResponseResult.error();
        }
    }

    @Operation(logContent = "OA审批结果回写SPMS", operateType = "修改")
    @RequestMapping("/updateOrderWerksStatus")
    @ApiOperation(value = "工厂请购单OA审批结果回写SPMS", notes = "OA 审批通过工厂请购单，oaBianhao：工厂请购单在 OA 编号；oaStatus：S - OA审批通通过；其他状态暂被忽略；\n" +
            "示例参数：oaBianhao = 938287, oaStatus = S \n" +
            "审批通过更新工厂请购单 spms 状态为：OA审批通过；更新完成后台自动将数据以 MQ 发送给 SRM。", httpMethod = "POST")
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateOrderWerksStatus(String oaBianhao, String oaStatus) {
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        try {
            /** OA 更新工厂请购单状态，如果 S 审批通过则工厂请购单更新成功后立马发送消息给 SRM */
            int result = iOrderWerksService.updateOrderWerksStatus(userId, oaBianhao, oaStatus);
            if (result == 1){
                /** OA 审批通过，SPMS 状态更新成功。则发送消息给 SRM 系统；
                 * 20211101 由MQ方式修改为REST请求方式
                 * */
                JSONObject restDataToSrm = restDataToSrm(oaBianhao);
                log.info("=======restDataToSrm=======" + restDataToSrm);
                JSONObject message = JSONObject.parseObject(iFeignServiceCommon.sendRestToSapCommon(restDataToSrm));
                log.info("=======message=======" + message);
                JSONObject RETURN_DATA = message.getJSONObject("RESPONSE").getJSONObject("RETURN_DATA");
                if (RETURN_DATA.containsKey("status") && "S".equals(RETURN_DATA.getString("status"))){
                    /** 状态 5 表示提交 SRM 成功；状态 8 表示提交 SRM 失败； **/
                    String status = String.valueOf(5);
                    iOrderWerksService.updateOrderWerksStatusByOaBianhao(userId, oaBianhao, status);
                    iSysLogMqService.addSysLogMq("3", "spms_srm_purchase_info", REQUEST_SEND_SRM,
                            "spms_srm_purchase_info", restDataToSrm.toJSONString(), message.toJSONString(), oaBianhao);
                    return ResponseResult.success("OA审批通过，提交SRM成功")
                            .add("orderWerks", iOrderWerksService.getByOaBianhao(oaBianhao));
                } else {
                    String status = String.valueOf(8);
                    iOrderWerksService.updateOrderWerksStatusByOaBianhao(userId, oaBianhao, status);
                    iSysLogMqService.addSysLogMq("3", "spms_srm_purchase_info", REQUEST_SEND_SRM_ERROR,
                            "spms_srm_purchase_info", restDataToSrm.toJSONString(), message.toJSONString(), oaBianhao);
                    return ResponseResult.error("OA审批通过，提交SRM出错")
                            .add("message", message.toJSONString())
                            .add("dataToSap", restDataToSrm.toJSONString());
                }

                /** 原MQ请求方式；状态 5 表示提交 SRM 成功；状态 8 表示提交 SRM 失败；
                int resp = sendMessageInterface.spms_srm_purchase_info2(oaBianhao);
                if (resp == 1){
                    String status = String.valueOf(5);
                    iOrderWerksService.updateOrderWerksStatusByOaBianhao(userId, oaBianhao, status);
                    return ResponseResult.success("OA审批通过，提交SRM成功");
                }
                if (resp == 0){
                    String status = String.valueOf(8);
                    iOrderWerksService.updateOrderWerksStatusByOaBianhao(userId, oaBianhao, status);
                    return ResponseResult.error("OA审批通过，提交SRM出错");
                }
                 **/
            }else if (result == -1){
                /** OA 审批不通过，SPMS 状态更新成功。不发送消息给 SRM 系统；*/
                return ResponseResult.success();
            }else if (result == -2){
                /** 对应单据已审批通通过，防止重复提交 */
                return ResponseResult.error("单据已审批通通过请勿重复提交");
            } else if (result == -3){
                return ResponseResult.success("单据审批通过不提交SRM");
            }
            /** result = 0 更新失败 */
            return ResponseResult.error("SPMS状态更新失败");
        } catch (FeignException feignException){
            feignException.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error("请求SRM失败 FeignException").add("error", feignException.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    JSONObject restDataToSrm(String oaBianhao){
        JSONObject doc = new JSONObject();
        Map<String, Object> DATA = iOrderWerksService.orderWerksToSrm2(oaBianhao);
        JSONObject REQUEST = new JSONObject();
        JSONObject ESB_ATTRS = new JSONObject();
        JSONObject REQUEST_DATA = new JSONObject();
        ESB_ATTRS.put("Application_ID", "00020000000004");
        ESB_ATTRS.put("Transaction_ID", UUID.randomUUID().toString());
        ESB_ATTRS.put("App_ID", "SPMS");

        REQUEST_DATA.put("Head", DATA.get("Head"));
        REQUEST_DATA.put("Items", DATA.get("Items"));
        REQUEST_DATA.put("Operation", "spms_srm_purchase_info");
        REQUEST_DATA.put("Type", "purchase_info");

        REQUEST.put("ESB_ATTRS", ESB_ATTRS);
        REQUEST.put("REQUEST_DATA", REQUEST_DATA);

        doc.put("REQUEST", REQUEST);
        return doc;
    }

    @Operation(logContent = "物料申请OA审批结果回写SPMS", operateType = "修改")
    @RequestMapping("/updateMaterialApplicationStatus")
    @ApiOperation(value = "物料申请单OA审批结果回写SPMS", notes = "OA 审批通过物料申请单，oaBianhao：物料申请单在 OA 编号；oaStatus：S - OA审批通通过；其他状态暂被忽略；\n" +
            "示例参数：oaBianhao = 938287, oaStatus = S \n" +
            "审批通过更新物料申请单 spms 状态为：OA审批通过；", httpMethod = "POST")
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateMaterialApplicationStatus(String oaBianhao, String oaStatus) {
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        try {
            /** OA 更新物料申请单状态，如果 S 审批通过则物料申请单更新成功 */
            int result = iMaterialApplicationService.updateMaterialApplicationStatus(userId, oaBianhao, oaStatus);
            if (result == 1){
                return ResponseResult.success("OA审批通过");
            }else if (result == -1){
                /** OA 审批不通过，SPMS 状态更新成功*/
                return ResponseResult.success();
            }else if (result == -2){
                /** 对应单据已审批通通过，防止重复提交 */
                return ResponseResult.error("单据已审批通通过请勿重复提交");
            }
            /** result = 0 更新失败 */
            return ResponseResult.error("SPMS状态更新失败");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @Operation(logContent = "盘亏盘盈申请OA审批结果回写SPMS", operateType = "修改")
    @RequestMapping("/updateInvChkAcStatus")
    @ApiOperation(value = "盘亏盘盈申请OA审批结果回写SPMS", notes = "盘亏盘盈申请OA审批结果回写SPMS，oaBianhao：物料申请单在 OA 编号；oaStatus：S - OA审批通通过；其他状态暂被忽略；\n" +
            "示例参数：oaBianhao = 938287, oaStatus = S \n" +
            "审批通过更新盘点盘亏盘盈单 spms 状态为：OA审批通过(5) OA审批失败(4)；", httpMethod = "POST")
    public ResponseResult updateInvChkAcStatus(String oaBianhao, String oaStatus) {
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        try {
            /** OA 更新盘盈盘亏单状态，如果 S 审批通过则盘盈盘亏单更新成功 */
            return iOverseaInvCheckActionService.updateOverseaInvChkAcByOa(userId, oaBianhao, oaStatus);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @Operation(logContent = "转储申请OA审批结果回写SPMS", operateType = "修改")
    @RequestMapping("/updateDumpStatus")
    @ApiOperation(value = "海外转储申请OA审批结果回写SPMS", notes = "海外转储申请OA审批结果回写SPMS，oaBianhao：物料申请单在 OA 编号；oaStatus：S - OA审批通通过；其他状态暂被忽略；\n" +
            "示例参数：oaBianhao = 1239464, oaStatus = S \n" +
            "审批通过更新转储任务状态 spms 状态为：OA驳回(4) OA审批通过(4)；", httpMethod = "POST")
    public ResponseResult updateDumpStatus(String oaBianhao, String oaStatus) {
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        try {
            /** OA 审批海外转储申请，如果 oaStatus = S 则审批通过，oaStatus = E 审批驳回，更新对应转储任务状态 */
            return iOverseaWhsDumpService.oaApproveWhsDump(oaBianhao, oaStatus, userId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    /**
     * http://192.168.106.90/external/#/external/oaview?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTc5MzQ0ODEsInVzZXJJZCI6Ijk5OTk0NyJ9.DcXsnU41dfKKbXWx15ZreieNy6hFhqyaR2ezsUuP_Bc&spmsId=GF03-2021-003
     */
    @GetMapping("/getOaApprovePage")
    @ApiOperation(value = "OA审批查看页面地址", notes ="工厂请购单OA审批页面\n\n" +
            "http://192.168.106.90/external/#/external/oaview?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTc5MzQ0ODEsInVzZXJJZCI6Ijk5OTk0NyJ9.DcXsnU41dfKKbXWx15ZreieNy6hFhqyaR2ezsUuP_Bc&spmsId=GF03-2021-003")
    public void updateOrderWerksStatus() {

    }

    @RequestMapping("/updateSpmsUserInfo")
    @ApiOperation(value = "实时同步用户OA信息到SPMS",notes = "实时同步用户OA信息到SPMS",
            httpMethod = "GET")
    public ResponseResult updateSpmsUserInfo(String userId) {
        if (StringUtils.isEmpty(userId)){
            return ResponseResult.error("请求参数不能为空");
        }
        try{
            OaService oaService = new OaService();
            Map<String, Object> map = oaService.getUserInfo(userId);
            if (map == null || map.size() == 0){
                return ResponseResult.error("OA返回信息错误");
            }
            return iSpmsUserService.updateSpmsUserInfo(map);
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

//    @Autowired
//    IUUserRoleService iuUserRoleService;
//
//    @RequiresRoles(value = {"oa"})
//    @RequestMapping("/getRequestDtl")
//    @ApiOperation(value = "获取请购单详情",notes = "username", httpMethod = "GET")
//    public ResponseResult getRequestDtl(String userid, String applicantId) {
//        Set<String> roleSet = new HashSet<String>();
//        for (URole r : iuUserRoleService.getRoleById(userid)) {
//            roleSet.add(r.getName());
//        }
//        System.out.println(roleSet);
//        if (roleSet.contains("oa"))
//            return ResponseResult.success().add("applicantId", applicantId + " 详情信息，SKU + Qty ......");
//        else
//            return ResponseResult.error("Access denied.");
//    }

//    @RequestMapping("/getUserInfo")
//    @ApiOperation(value = "获取用户详细信息",notes = "获取指定工号的用户详细信息，示例 userId = 999947",
//            httpMethod = "POST")
//    public ResponseResult getOrderScenario(String userId) {
//        OaService oaService = new OaService();
//        try{
//            return oaService.getUserInfo(userId);
//        } catch (Exception e){
//            return ResponseResult.error("请求异常请重试:" + e);
//        }
//    }

}
